<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>鉴赏管理</el-breadcrumb-item>
      <el-breadcrumb-item>鉴赏列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入鉴赏名称（模糊搜索）"
            v-model="queryInfo.query"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handlesearchEnjoy"
            ></el-button> </el-input
        ></el-col>
      </el-row>

      <!-- table表格 -->
      <el-table :data="enjoyList" border stripe>
        <!-- <el-table-column type="expand">
          <template slot-scope="scope">
            <el-descriptions title="其他信息" border style="padding: 10px">
              <el-descriptions-item label="商品描述">{{
                scope.row.description
              }}</el-descriptions-item>

            </el-descriptions>
          </template>
        </el-table-column> -->
        <el-table-column prop="id" width="60px"> </el-table-column>
        <el-table-column prop="goods_id" label="绑定商品id"> </el-table-column>
        <el-table-column prop="is_host" label="市场热门">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_host">热门</el-tag>
            <el-tag v-else style="opacity: 0"></el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="鉴赏名称"> </el-table-column>
        <el-table-column prop="delete_time" label="是否删除">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.delete_time" type="warning">是</el-tag>
            <el-tag v-else style="opacity: 0"></el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="500px">
          <template slot-scope="scope">
            <!-- 显示/修改信息 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="min"
              @click="handleShowEnjoyDialog(scope.row)"
              >信息</el-button
            >

            <!-- 显示/修改参图片-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="min"
              @click="handleShowSwiperDialog(scope.row.id)"
              >图片</el-button
            >

            <!-- 显示/修改商品详细信息 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="min"
              @click="handleShowDetailsDialog(scope.row)"
              >详细</el-button
            >

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="min"
              @click="handleDelete(scope.row.id, scope.row.delete_time)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-size="queryInfo.pageSize"
        :page-sizes="[3, 5, 10, 20]"
        layout="total, sizes,prev, pager, next,jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 修改/显示鉴赏信息 -->
    <el-dialog
      title="修改鉴赏信息"
      :visible.sync="editInfoDialog"
      @close="handleCloseEditInfo"
      width="80%"
    >
      <el-form
        label-width="80px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="鉴赏名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入鉴赏名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="种类地区" prop="logistics_price">
          <el-select
            v-model="editForm.places"
            filterable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="绑定商品id" prop="goods_id">
          <el-select
            v-model="editForm.goods_id"
            filterable
            remote
            reserve-keyword
            clearable
            placeholder="请输入关键词"
            :remote-method="handSearchGoodsNameList"
          >
            <el-option
              v-for="item in goodsNameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="市场流行" prop="is_host">
          <!-- v-model="editForm.is_host" -->
          <el-switch
            v-model="editForm.is_host"
            active-text="是"
            inactive-text="否"
          >
          </el-switch>
        </el-form-item>

        <el-form-item label="鉴赏描述" prop="description">
          <Tinymce
            :height="300"
            v-model="editForm.description"
            ref="tinymce"
          ></Tinymce>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editInfoDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleUpdateInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改轮播图 -->
    <el-dialog
      title="修改鉴赏轮播图信息"
      :visible.sync="editSwiperDialog"
      @close="handleCloseEditSwiper"
      width="70%"
    >
      <div class="goods-swiper-wrapper">
        <div
          class="image-wrapper"
          v-for="(image, index) in swiperList"
          :key="image.id"
        >
          <div class="close" @click="handleCloseSwiper(image.id, index)">
            <i class="el-icon-circle-close"></i>
          </div>

          <!-- <div class="left" @click="handleUpSwiper(image.id, index)">
            <i class="el-icon-caret-left"></i>
          </div> -->
          <div class="image">
            <img :src="image.url" />
            <!-- <div class="image-show" @click="handleShowSwiper(image.url)">
              <span>点击浏览图片</span>
            </div> -->
          </div>

          <!-- <div class="right" @click="handleDownSwiper(image.id, index)">
            <i class="el-icon-caret-right"></i>
          </div> -->
        </div>
      </div>

      <!-- handleUploadSwiper -->
      <span slot="footer" class="dialog-footer">
        <el-upload
          style="display: inline-block; margin-right: 10px"
          multiple
          :show-file-list="false"
          action="#"
          :http-request="handleUploadEnjoySwiper"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <el-button type="primary" @click="editSwiperDialog = false"
          >退 出</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改详细信息 -->

    <el-dialog
      title="修改鉴赏详细信息"
      :visible.sync="editDetailsDialog"
      @close="handleCloseEditDetails"
      width="80%"
    >
      <Tinymce :height="500" v-model="editDetails.info"></Tinymce>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editDetailsDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleUpdateDetails">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '../tinymce/TinymceComponent.vue'
export default {
  components: { Tinymce },
  data() {
    const validateArr = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('该参数列表不能为空'))
      } else {
        callback()
      }
    }
    return {
      enjoyList: [],
      goodsNameList: [],
      swiperList: [],
      currSwiper: [],
      currEnjoyId: '',
      options: [
        {
          value: '广东',
          label: '广东'
        },
        {
          value: '广西',
          label: '广西'
        },
        {
          value: '海南',
          label: '海南'
        },
        {
          value: '四川',
          label: '四川'
        },
        {
          value: '福建',
          label: '福建'
        },
        {
          value: '云南',
          label: '云南'
        }
      ],
      total: 0,
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      editForm: {
        id: '',
        places: '',
        name: '',
        goods_id: '',
        is_host: false,
        description: '',
        details: ''
      },
      editFormRules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入商品描述',
            trigger: 'blur'
          }
        ],
        count: [
          {
            required: true,
            message: '请输入商品库存',
            trigger: 'blur'
          }
        ],

        swiperList: [
          {
            required: true,
            message: '请添加商品轮播图',
            validator: validateArr,
            trigger: 'blur'
          }
        ],

        details: [
          {
            required: true,
            message: '请输入商品详细信息',
            trigger: 'blur'
          }
        ]
      },
      editDetails: {
        info: '',
        id: ''
      },
      editInfoDialog: false,
      editSwiperDialog: false,
      editDetailsDialog: false
    }
  },
  mounted() {
    this.getEnjoyList()
  },
  methods: {
    async getEnjoyList() {
      const { data: res } = await this.$http.get('/getEnjoyList', {
        params: this.queryInfo
      })
      if (res.status !== 200) {
        return this.$message.error('获取鉴赏列表失败!')
      }
      // console.log(res)
      this.enjoyList = res.data.data
      // console.log(this.goodsList, res.data.data, res)

      this.total = res.data.totalNum
      this.$message.success('获取鉴赏列表成功!')
    },

    async getEnjoyImageList(id) {
      const { data: res } = await this.$http.get('/getEnjoyImageList/' + id)
      if (res.status !== 200) {
        return this.$message.error('获取鉴赏图片列表失败!')
      }
      // console.log(res)
      this.swiperList = res.data
      // console.log(this.goodsList, res.data.data, res)

      this.$message.success('获取鉴赏图片列表成功!')
    },

    async handleUpdateInfo() {
      // console.log(this.editForm)
      console.log(this.$refs)

      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return

        this.editForm.places = this.editForm.places.join(',')
        this.editForm.goods_id =
          this.editForm.goods_id === '' ? 0 : this.editForm.goods_id

        const { data: res } = await this.$http.post('/updateEnjoyInfo', {
          ...this.editForm
        })
        if (res.status !== 200) {
          this.$message.error('更新鉴赏信息失败')
          return
        }

        this.$message.success('更新鉴赏信息成功')
        this.getEnjoyList()
        this.editInfoDialog = false
      })
    },

    async handleUpdateDetails() {
      if (this.editDetails.info.length === 0 || this.editDetails.info === '') {
        return this.$message.info('详细信息不能为空')
      }

      const formData = new FormData()
      const urls = this.extractBlobUrls(this.editDetails.info)
      // console.log(urls)
      // console.log(this.editDetails)

      for (let i = 0; i < urls.length; i++) {
        const file = await this.blobUrlToFile(urls[i], `file${i}.png`)
        formData.append('images[]', file)
      }

      formData.append(
        'details',
        JSON.stringify({
          enjoy_id: this.editDetails.id,
          info: this.editDetails.info
        })
      )

      const { data: res } = await this.$http.post(
        '/updateEnjoyDetails',
        formData
      )
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }
      this.editDetailsDialog = false
      this.getEnjoyList()
      return this.$message.success(res.message)
    },

    async handleDelete(id, deleteTime) {
      console.log(id)
      const confirmRes = await this.$confirm(
        '是否（恢复/删除）该鉴赏信息',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 如果用户确认删除，返回的是文本confirm
      // 如果用户取消删除，返回的是cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 删除

      const { data: res } = await this.$http.post('/deleteOrRecoverEnjoy', {
        id: id,
        flag: deleteTime == null
      })
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }

      this.$message.success(res.message)
      this.getEnjoyList()
    },

    handleShowDetailsDialog(enjoy) {
      this.editDetails.id = enjoy.id
      this.editDetails.info = enjoy.content
      this.editDetailsDialog = true
    },

    handleCloseEditDetails() {
      this.editDetails = {
        id: '',
        details: ''
      }
    },

    handleShowEnjoyDialog(enjoy) {
      // console.log(enjoy)
      const places = enjoy.places.split(',')
      this.editForm = {
        id: enjoy.id,
        places: places,
        name: enjoy.name,
        goods_id: enjoy.goods_id,
        is_host: enjoy.is_host,
        description: enjoy.description
      }

      this.editInfoDialog = true
    },

    async handleUploadEnjoySwiper(e) {
      const formData = new FormData()
      formData.append('swiper', e.file)
      formData.append('enjoyId', this.currEnjoyId)

      const { data: res } = await this.$http.post(
        '/uploadEnjoySingleSwiperByEId',
        formData
      )
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }
      this.$message.success(res.message)
      this.getSwiperData(this.currEnjoyId)
    },

    async handSearchGoodsNameList(e) {
      const { data: res } = await this.$http.get('/getGoodsNameList?query=' + e)

      if (res.status !== 200) {
        this.$message.error(res.message)
        return
      }

      this.goodsNameList = res.data.data
    },

    handleCloseEditInfo() {
      this.editForm = {
        places: '',
        name: '',
        goods_id: '',
        is_host: false,
        description: '',
        swiperList: [],
        details: ''
      }
    },

    async handlesearchEnjoy() {
      this.queryInfo.pageNum = 1
      this.getEnjoyList()
    },

    async getSwiperData(enjoyId) {
      const { data: res } = await this.$http.get(
        '/getEnjoyImageList/' + enjoyId
      )
      // console.log(res)
      if (res.status !== 200) {
        return this.$message.error(res.message)
      }

      this.swiperList = res.data
      this.currEnjoyId = enjoyId
      this.swiperList.sort((a, b) => {
        return a.sort_index - b.sort_index
      })
    },

    async handleShowSwiperDialog(enjoyId) {
      this.getSwiperData(enjoyId)
      this.editSwiperDialog = true
    },

    async handleCloseSwiper(id, index) {
      let confirm

      try {
        confirm = await this.$confirm('是否参数该轮播图?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        // console.log('取消')
        return
      }
      if (confirm === 'confirm') {
        const { data: res } = await this.$http.post('/deleteEnjoyImage/' + id)

        if (res.status !== 200) {
          this.$message.error(res.message)
          return
        }

        this.swiperList.splice(index, 1)
        this.$message.success(res.message)
      }
    },

    handleCloseEditSwiper() {
      this.swiperList = []
    },

    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getEnjoyList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getEnjoyList()
    },
    extractBlobUrls(html) {
      const regex = /<img[^>]*src=["'](blob:[^"'>]*)["'][^>]*>/gi
      const blobUrls = []
      let match

      while ((match = regex.exec(html))) {
        if (match[1]) {
          blobUrls.push(match[1])
        }
      }
      return blobUrls
    },

    async blobUrlToFile(blobUrl, fileName) {
      const response = await fetch(blobUrl)
      const blob = await response.blob()
      return new File([blob], fileName, { type: blob.type })
    }
  }
}
</script>

<style lang="less" scoped>
.goods-swiper-wrapper {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;

  .image-wrapper {
    cursor: pointer;
    display: inline-flex;
    width: 100%;
    height: 225px;
    position: relative;
    overflow: hidden;

    .close {
      width: 35px;
      height: 35px;
      // background-color: #8c939d;
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: 0;
      right: 0;
      font-size: 30px;
      color: #fff;
      z-index: 20;
    }

    .close:hover {
      color: #409eff;
    }

    .image {
      // pointer-events: all;
      width: 100%;
      height: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.tox {
  z-index: 9999 !important;
}
</style>
